from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
import json
from web.models import Reward, Activity, ParticipationRecord
from django import forms
from django.forms.models import model_to_dict
from web import utils
tools = utils.Utils()
class RewardForm(forms.ModelForm):
    class Meta:
        model = Reward
        fields = ['activity', 'reward_name', 'reward_type', 'quantity', 'remaining', 'description', 'image']

@csrf_exempt
@require_http_methods(["POST"])
def create_reward(request):
    """创建奖励"""
    try:
        data = request.POST
        activity_id = data.get('activity')
        try:
            activity = Activity.objects.get(id=activity_id)
        except Activity.DoesNotExist:
            return JsonResponse({'code': 404, 'message': '活动不存在'})
            
        reward_form = RewardForm(data=data, files=request.FILES)
        if reward_form.is_valid():
            reward = reward_form.save()
            # 返回创建数据
            reward_dict = model_to_dict(reward)
            reward_dict["created_at"] = reward.created_at.strftime("%Y-%m-%d %H:%M:%S")
            reward_dict["updated_at"] = reward.updated_at.strftime("%Y-%m-%d %H:%M:%S")
            print(reward_dict)
            reward_dict["image"] = reward.image.url if reward.image else None
            return JsonResponse({'code': 200, 'message': '奖励创建成功', 'data': reward_dict})
        else:
            print(reward_form.errors)
            return JsonResponse({'code': 400, 'message': '奖励创建失败', 'errors': reward_form.errors})
        
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})

@require_http_methods(["GET"])
def reward_list(request, activity_id):
    """获取活动的奖励列表"""
    try:
        rewards = Reward.objects.filter(activity_id=activity_id)
        reward_list = [{
            'id': reward.id,
            'reward_name': reward.reward_name,
            'reward_type': reward.reward_type,
            'quantity': reward.quantity,
            'remaining': reward.remaining,
            'image': reward.image.url if reward.image else None,
            'description': reward.description
        } for reward in rewards]
        
        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': reward_list
        })
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)}) 

# 获取我的奖励
def my_rewards(request):
    if request.method == 'GET':
        user_id = request.GET.get('user_id')
        rewards = ParticipationRecord.objects.filter(user_id=user_id)
        reward_list = []
        for reward in rewards:
            """
            要知道我参加过哪一些活动

            """
            

            # 奖励
            if  reward.status in [1,2,3]:
                reward_dict = model_to_dict(reward)
                activity_dict = model_to_dict(reward.activity)
                activity_dict['created_at'] = reward.activity.created_at.strftime("%Y-%m-%d %H:%M:%S")
                activity_dict['updated_at'] = reward.activity.updated_at.strftime("%Y-%m-%d %H:%M:%S")
                activity_dict['cover_image'] = reward.activity.cover_image.url if reward.activity.cover_image else None
                del activity_dict['user_id']
                reward_dict['created_at'] = reward.created_at.strftime("%Y-%m-%d %H:%M:%S")
                reward_dict["activity"] = activity_dict
                reward_dict["status"] = reward.get_status_display()
                # 有一些活动是没有奖励的
                if reward.reward:
                    reward_dict['reward'] = model_to_dict(reward.reward)
                    reward_dict['reward']['image'] = reward.reward.image.url if reward.reward.image else None
                    reward_dict['reward']['created_at'] = reward.reward.created_at.strftime("%Y-%m-%d %H:%M:%S")
                    reward_dict['reward']['updated_at'] = reward.reward.updated_at.strftime("%Y-%m-%d %H:%M:%S")
                reward_dict["completion_time"] = reward.completion_time.strftime("%Y-%m-%d %H:%M:%S")
                reward_list.append(reward_dict)

        return JsonResponse({'code': 200, 'message': '获取成功', 'data': reward_list})
    else:
        return JsonResponse({'code': 405, 'message': '方法不允许'})


# 编辑或删除奖励
@csrf_exempt
@require_http_methods(["POST"])
def edit_reward(request):
    data = request.POST
    if data.get('is_delete') == 'true':
        reward_id = data.get('reward_id')
        reward = Reward.objects.filter(id=reward_id).first()
        if reward:
            reward.delete()
            return JsonResponse({'code': 200, 'message': '奖励删除成功'})
        else:
            return JsonResponse({'code': 404, 'message': '奖励不存在'})
    activity_id = data.get('activity_id')
    if not activity_id:
        return JsonResponse({'code': 400, 'message': '活动id不能为空'})
    activity = Activity.objects.filter(id=activity_id).first()
    if not activity:
        return JsonResponse({'code': 404, 'message': '活动不存在'})
    reward_id = data.get('reward_id')
  
    if not reward_id:
        return JsonResponse({'code': 400, 'message': '奖励id不能为空'})
    reward = Reward.objects.filter(id=reward_id).first()
    if not reward:
        return JsonResponse({'code': 404, 'message': '奖励不存在'})
    data = tools.QueryDict_Add(data, 'activity', activity)
    reward_form = RewardForm(data=data, files=request.FILES, instance=reward)
   
    if reward_form.is_valid():
        reward_form.save()
        # 判断image有没有，如果有但是没有值，说明要删除掉数据库的图片
        if data.get('image') == '':
            reward.image = None
            reward.save()   
        reward_dict = model_to_dict(reward)
        reward_dict["created_at"] = reward.created_at.strftime("%Y-%m-%d %H:%M:%S")
        reward_dict["updated_at"] = reward.updated_at.strftime("%Y-%m-%d %H:%M:%S")
        reward_dict["image"] = reward.image.url if reward.image else None
        return JsonResponse({'code': 200, 'message': '奖励编辑成功', 'data': reward_dict})
    else:
        print(reward_form.errors)
        return JsonResponse({'code': 400, 'message': '奖励编辑失败'})
    
